import { _decorator, Camera, Component, screen, misc, Node, UITransform, view, ResolutionPolicy } from 'cc';
const { ccclass, property } = _decorator;

@ccclass('CameraFollow')
export class CameraFollow extends Component {

    @property(Node)
    private player: Node = null;  // 玩家角色节点
    @property(Node)
    map: Node = null;     // 地图节点
    @property({type: Camera})
    camera: Camera = null;     // 地图节点

    private mapWidth: number = 0;
    private mapHeight: number = 0;
    private _cameraMaxX: number = 0;
    private _cameraMaxY: number = 0;

    
    start() {
        // view.setDesignResolutionSize(640, 960, ResolutionPolicy.SHOW_ALL);

        // 获取地图尺寸
        const mapSize = this.map.getComponent(UITransform).contentSize;
        console.log("地图大小:"+ mapSize)
        this.mapWidth = mapSize.width;
        this.mapHeight = mapSize.height;
        
        // 获取和设置当前窗口的物理像素尺寸
        const visibleWidth = view.getVisibleSize().width;
        const visibleHeight = view.getVisibleSize().height;
        console.log("VisibleSize:"+ view.getVisibleSize())

        // 可移动范围 = 地图大小-视图大小
        this._cameraMaxX = (this.mapWidth - visibleWidth)/2;
        this._cameraMaxY = (this.mapHeight- visibleHeight)/2;
        console.log('镜头可移动范围：'+ this._cameraMaxX,  this._cameraMaxY)
    }
    
     update(deltaTime: number) {
        // 获取玩家位置
        const playerPos = this.player.getPosition();
       
        //摄像头
        const x = Math.max(-this._cameraMaxX, Math.min(this._cameraMaxX, playerPos.x))
        const y = Math.max(-this._cameraMaxY, Math.min(this._cameraMaxY, playerPos.y))
        this.camera.node.setPosition(x,y);
    }
}

